package com.gaxy.wechat.handler;

import com.gaxy.wechat.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户发送文本消息handler
 *
 * @author Gaxy
 * @create 2024/06/14/上午 11:01
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WeChatMsgHandler {

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;


    @Override
    public WeChatMsgTypeEnum getMsgType() {
        return WeChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收文本消息事件");
        String content = msgMap.get("Content");
        //如果用户发送的不是"验证码"三个字，则不返回字符串
        if (!KEY_WORD.equals(content)) {
            return "";
        }
        String toUserName = msgMap.get("ToUserName");
        String fromUserName = msgMap.get("FromUserName");
        //生成随机的四位数验证码
        Random random = new Random();
        int verificationCode = random.nextInt(1000);
        //将验证码存入Redis中
        String verificationCodeKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(verificationCode));
        //设置存储时间5分钟
        redisUtil.setNx(verificationCodeKey,fromUserName,5L, TimeUnit.MINUTES);
        String numContent = "您当前的验证码是：" + verificationCode + "！ 5分钟内有效。";;
        String msg =
                "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return msg;
    }
}
